using System;
using System.Collections.Generic;
using System.Text;
using Instedd.Labs.Geo.Library.Rss;
using Instedd.Labs.Geo.Library.Kml;
using System.Globalization;

namespace Instedd.Labs.Geo.Library.Sms
{
    public class RssManager
    {
        private Item CreateItem(string name, LatLong location, IEnumerable<SmsExtension> messages, RssFactorySettings settings)
        {
            SmsExtension lastUserMessage = null;

            string itemDescription = BubbleDescriptionGenerator.GetDescription(name, location, messages, settings , out lastUserMessage);
            
            Item item = new Item(Guid.NewGuid(), name, name, itemDescription, lastUserMessage.Sms.Time, null, location, null);

            return item;
        }

        public RssFormat CreateGeoRss(IEnumerable<SmsExtension> messages)
        {
            return CreateGeoRss(messages, new RssFactorySettings());
        }

        public RssFormat CreateGeoRss(IEnumerable<SmsExtension> messages, RssFactorySettings settings)
        {
            RssFormat rssFormat = new RssFormat();
            Channel channel = new Channel();
            channel.LastBuildDate = DateTime.Now;
            channel.Title = "SMS";
            channel.Link = "#";
            channel.PubDate = DateTime.Now;
            channel.Description = "SMS";
            rssFormat.Channels.Add(channel);

            Dictionary<string, Dictionary<LatLong, List<SmsExtension>>> messagesGroupBySenderNameAndLocation = SmsMessagesManager.GetMessageGroupBySenderNameAndLocation(messages);

            foreach (string senderName in messagesGroupBySenderNameAndLocation.Keys)
            {
                Line path = new Line();

                foreach (LatLong location in messagesGroupBySenderNameAndLocation[senderName].Keys)
                {
                    path.Coordinates.Add(location);

                    Item item = CreateItem(senderName, location, messagesGroupBySenderNameAndLocation[senderName][location], settings);

                    channel.Items.Add(item);      
                }

                if (path.Coordinates.Count > 1)
                {
                    channel.Items[channel.Items.Count - 1].Line = path;
                }
            }

            return rssFormat;
        }
    }
}
